package com.example.demo;

import com.alibaba.fastjson2.JSONObject;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


public class ClipboardServer {
    private final static Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

    public static void main(String[] args) throws IOException {
        int port = 30000;
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(port), 0);
        httpServer.createContext("/read", new ReadHandler());
        httpServer.createContext("/write", new WriteHandler());
        httpServer.start();

        System.out.println("Server started : http://" +InetAddress.getLocalHost().getHostAddress()+":"+ port);
    }

   static class ReadHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String response = "";

            // 检查剪贴板中的内容是否可转换为文本
            if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
                // 获取剪贴板中的文本内容
                try {
                    response = (String) clipboard.getData(DataFlavor.stringFlavor);
                } catch (UnsupportedFlavorException e) {
                    throw new RuntimeException(e);
                }
            }

            // 检查剪贴板内容是否为图片
            if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor)) {
                // 获取剪贴板内容
                Transferable transferable = clipboard.getContents(null);

                // 将内容转换为Image对象
                Image image;
                try {
                    image = (Image) transferable.getTransferData(DataFlavor.imageFlavor);
                } catch (UnsupportedFlavorException e) {
                    throw new RuntimeException(e);
                }

                // 创建字节数组输出流
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                // 将Image写入到字节数组输出流
                ImageIO.write((RenderedImage) image, "png", outputStream);

                // 获取字节数组
                byte[] imageBytes = outputStream.toByteArray();

                // 关闭输出流
                outputStream.close();

                // 设置响应头为image/png
                exchange.getResponseHeaders().set("Content-Type", "image/png");
                exchange.sendResponseHeaders(200, imageBytes.length);

                // 写入字节数组到响应流中
                OutputStream output = exchange.getResponseBody();
                output.write(imageBytes);
                output.flush();
                output.close();

                return;
            }

            // 设置响应头为text/plain
            exchange.getResponseHeaders().set("Content-Type", "text/plain;charset=utf-8");
            exchange.sendResponseHeaders(200, response.getBytes().length);

            // 写入响应内容
            OutputStream output = exchange.getResponseBody();
            output.write(response.getBytes());
            output.flush();
            output.close();
        }
    }

   static class WriteHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {

            byte[] bytes = exchange.getRequestBody().readAllBytes();
            String data=new String(bytes, StandardCharsets.UTF_8);

            data=Optional.ofNullable(JSONObject.parseObject(data))
                    .map(jsonObject -> jsonObject.getString("data"))
                    .orElse("");

            // 创建一个字符串数据转移对象
            StringSelection selection = new StringSelection(data);

            // 将数据设置到剪贴板
            clipboard.setContents(selection, null);

            // 设置响应头为text/plain
            exchange.getResponseHeaders().set("Content-Type", "text/plain");
            exchange.sendResponseHeaders(200, "OK".getBytes().length);

            // 写入响应内容
            OutputStream output = exchange.getResponseBody();
            output.write("OK".getBytes());
            output.flush();
            output.close();
        }

    }
}